<!--多文件上传按钮组件，上传到服务器，此组件必须向插槽中插入其它元素，否则页面看不见-->
<template>
  <a-upload
    :action="uploadUrl"
    :headers="headers"
    :accept="accept"
    :disabled="disabled"
    :showUploadList="showUploadList"
    :multiple="multiple"
    :data="data"
    :beforeUpload="beforeUpload"
    @change="handleChange"
  >
    <slot></slot>
  </a-upload>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'AntUpload',
  props: {
    /**
     * 是否禁用
     */
    disabled: {
      type: Boolean,
      default: false
    },
    /**
     * 上传接口地址
     */
    action: {
      type: String,
      default: '/file/upload'
    },
    /**
     * 允许上传的文件类型
     */
    accept: {
      type: String,
      default: '.txt,.xls,.xlsx,.doc,.docx,.pfd,.zip,.ppt,.pptx,.rar,.png,.jpg,.pdf'
    },
    /**
     * 多文件上传
     */
    multiple: {
      type: Boolean,
      default: true
    },
    /**
     * 附件上传时需要传递到后台的参数,传入tableName,关联的业务表名称
     */
    data: {
      type: Object,
      default: () => {
        return {
          tableName:null
        }
      }
    },
    /**
     * 是否显示上传文件列表
     */
    showUploadList: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      // 上传的图片服务器地址
      uploadUrl: process.env.VUE_APP_BASE_API,
      headers: {
        "Api-Admin-Token":  getToken(),
      },
    }
  },
  created() {
    this.uploadUrl=process.env.VUE_APP_BASE_API+this.action
  },
  computed: {

  },
  methods: {
    /**
     * 附件上次前验证是否允许
     * @param file
     * @param fileList
     * @returns {boolean}
     */
    beforeUpload(file, fileList) {
      if (this.accept === '') {
        return true
      }
      let accept = this.accept.split(',')
      for (let i = 0; i < fileList.length; i++) {
        let index = fileList[i].name.lastIndexOf('.')
        let type = fileList[i].name.substr(index)
        if (accept.indexOf(type) === -1) {
          this.$message.error('不允许上传' + type + '格式文件!')
          return false
        }
      }
      return true
    },
    /**
     * 文件变化处理
     * @param obj
     */
    handleChange(obj) {
      this.$emit('change', obj)
    }
  }
}
</script>

<style lang="less" scoped>

</style>
